package com.fz.us.oa.web.controller.mp;

import com.fz.us.admin.base.bean.SystemConfig;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.base.utils.StringUtils;
import com.fz.us.admin.company.bean.EnumManage;
import com.fz.us.admin.company.mp.WxEchoMpMessageRouter;
import com.fz.us.admin.company.mp.WxMpInCacheConfigStorage;
import com.fz.us.admin.company.service.jms.AdvancedNotifyMessageProducer;
import com.fz.us.base.service.memcached.SpyMemcachedClient;
import com.fz.us.base.util.Identities;
import com.fz.us.oa.web.controller.BaseController;
import fz.me.chanjar.weixin.common.api.WxConsts;
import fz.me.chanjar.weixin.common.exception.WxErrorException;
import fz.me.chanjar.weixin.mp.api.WxMpService;
import fz.me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import fz.me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import fz.me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import fz.me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import fz.me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

/**
 * 控制器 - 登录
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-07-29 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/mp")
public class WechatController extends BaseController {

    private static final long serialVersionUID = -2698058660432614870L;

    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpInCacheConfigStorage wxMpConfigStorage;
    @Autowired
    private WxEchoMpMessageRouter wxMpMessageRouter;
    @Autowired
    private AdvancedNotifyMessageProducer notifyMessageProducer;


    @RequestMapping(value = "wechat", method = RequestMethod.GET)
    public String wechat(Model model, HttpServletResponse response, HttpServletRequest request, String code) throws IOException {
        LogUtil.info("{wechart start}");
        LogUtil.info("{code}"+code);
        Enumeration<String> paramter=request.getParameterNames();
        while(paramter.hasMoreElements()){
            String v=(String)paramter.nextElement();
            com.fz.us.base.util.LogUtil.info("{request参数}" + v);
        }
        String method = request.getMethod();
        boolean isPostMethod = "POST".equalsIgnoreCase(method);
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        //LogUtil.info(signature + " " + nonce + " " + timestamp + " getToken:" + wxMpConfigStorage.getToken());
        getResponse().setContentType("text/html;charset=utf-8");
        getResponse().setStatus(HttpServletResponse.SC_OK);
/*        try {
            LogUtil.info(SHA1.gen(wxMpConfigStorage.getToken(), timestamp, nonce));
        } catch (NoSuchAlgorithmException e) {

        }*/
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            return ajaxText("非法请求");
        }
        if (!isPostMethod) {
            //Get
            String echostr = request.getParameter("echostr");
            //LogUtil.info("echostr"+echostr);
            if (StringUtils.isNotBlank(echostr)) {
                // 说明是一个仅仅用来验证的请求，回显echostr
                return ajaxText(echostr);
            }
        } else {
            //POST
            String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ?
                    "raw" :
                    request.getParameter("encrypt_type");
            //System.out.println("encryptType:"+encryptType);
            WxMpXmlMessage inMessage = null;
            if ("raw".equals(encryptType)) {
                // 明文传输的消息
                try {
                    inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            } else if ("aes".equals(encryptType)) {
                // 是aes加密的消息
                String msgSignature = request.getParameter("msg_signature");
                inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature);
            } else {
                return ajaxText("不可识别的加密类型");
            }
            //LogUtil.info("{inMessage.getFromUserName()}"+inMessage.getFromUserName()  + " {inMessage.getToUserName()}" + inMessage.getToUserName());
            LogUtil.info("{inMessage.getEvent()}" + inMessage.getEvent()+"key"+ inMessage.getEventKey());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            String seceneId="";
//            LogUtil.info("{encryptType}" + encryptType + "{outMessage}" + outMessage.toXml());
            //拿到二维码secene_id,已关注
            if(StringUtils.equals("SCAN",inMessage.getEvent())){
                seceneId=inMessage.getEventKey();
            }else if(org.apache.commons.lang3.StringUtils.equals("subscribe",inMessage.getEvent())){
                WxMpCustomMessage message = new WxMpCustomMessage();
                message.setMsgType(WxConsts.CUSTOM_MSG_TEXT);
                message.setToUser(inMessage.getFromUserName());
                String link = "<a href=\""+wxMpConfigStorage.getHttpHost()+"/"+systemConfig.getWebroot()+"/mp/account/resetMp?_="+ Identities.randomBase62(8)+"\">进行注册</a>";
                message.setContent("[微笑] 欢迎您关注OA系统，请点此" + link);
                notifyMessageProducer.sendQueue(message, EnumManage.NotifyKeyEnum.wxMpCustomMessage.name());
                LogUtil.info("inMessage.getFromUserName():" + inMessage.getFromUserName());
            }
            if (outMessage != null) {
                if ("raw".equals(encryptType)) {
                    response.getWriter().write(outMessage.toXml());
                } else if ("aes".equals(encryptType)) {
                    response.getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage));
                }
                return null;
            }
            return null;
        }
        return null;
    }



}
